/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmp.arena;

import com.cmp.arena.controls.BallControl;
import com.cmp.core.constants.CollisionGroupsConstants;
import com.cmp.player.controls.CharacterRigidBodyControl;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.GhostControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
/**
 *
 * @author krummer
 */
public class BallFactory {
    public static void makeBall(Node ball, AssetManager assets) {
        
        //add Model
        ball.attachChild(assets.loadModel("Models/sphere.j3o"));
        
        //add physics
        CharacterRigidBodyControl body = new CharacterRigidBodyControl(1.f,2.f,1.f);
        ball.addControl(body);
        body.setFriction(1.f);
        body.setCollisionGroup(CollisionGroupsConstants.BALL);
        body.setCollideWithGroups(CollisionGroupsConstants.MAP);
        ball.addControl(new BallControl());
        SphereCollisionShape shape = new SphereCollisionShape(1.f);
        GhostControl ghostControl = new GhostControl(shape) {
            @Override 
            public void update(float tpf) {
                super.update(tpf);
                for(PhysicsCollisionObject otherObject:this.getOverlappingObjects()) {
                    if(otherObject instanceof CharacterRigidBodyControl) {
                        Spatial other = ((CharacterRigidBodyControl)otherObject).getSpatial();
                        if(other.getUserData("isPlayer") != null) {
                            this.spatial.removeFromParent();
                            this.spatial.setLocalTranslation(new Vector3f(0.f, 3.f, 0.f));
                            this.spatial.getControl(RigidBodyControl.class).setEnabled(false);
                            this.setEnabled(false);
                            ((Node)other).attachChild(this.spatial);
                            break;
                        }
                    }
                }
            }
        };
        ghostControl.setCollideWithGroups(CollisionGroupsConstants.PLAYER);
        ghostControl.setCollisionGroup(CollisionGroupsConstants.TRIGGER);
        ball.addControl(ghostControl);
    }
}
